package com.qf.framwork.cases.impl;

import com.qf.framwork.cases.ParamsCases;
import com.qf.framwork.uploader.MultipartFile;
import org.apache.commons.fileupload.FileItem;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * description: 上传类型转换器
 * author: Ken
 * 公众号：Java架构栈
 */
public class MultipartFileParamsCases implements ParamsCases {

    @Override
    public Object getParams(Method m, String name, Map<String, FileItem> itemMap, HttpServletRequest request, HttpServletResponse response) {
        if (itemMap != null && itemMap.containsKey(name)) {
            FileItem fileItem = itemMap.get(name);
            if (fileItem.isFormField()) return null;

            try {
                MultipartFile multipartFile = new MultipartFile()
                        .setFileName(fileItem.getName())
                        .setFileLength(fileItem.getSize())
                        .setInputStream(fileItem.getInputStream());

                return multipartFile;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
